﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HPortal.Lib;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;

namespace HPortal.Backend
{
    public partial class ChannelList : System.Web.UI.Page
    {
        private DataTable channel;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                channel = getChannel();
                LoadMenu(trvChannelList.Nodes, 0);
            }
        }


        private DataTable getChannel()
        {
            try
            {
                string where = string.Empty;
                if (this.Context.User.Identity.IsAuthenticated)
                {
                    string[] arrRoleName = Roles.GetRolesForUser(this.Context.User.Identity.Name);
                    foreach (string roleName in arrRoleName)
                    {
                        where += DatabaseHelper.EscapeQuoteUnicode(roleName) + ",";
                    }

                }
                where = where.Remove(where.Length - 1);
                where = "WHERE ChannelID IN (SELECT DISTINCT ChannelID FROM [ChannelRole] WHERE ([Role] IN (" + where + ") AND (Edited=1 OR Approved=1 OR Administrated=1)))";
                string query = "SELECT * FROM [Channel] " + where + " ORDER BY Language,[ParentID],[Priority],[ChannelID]";
                return DatabaseHelper.Select(query);
            }
            catch {
                return null;
            }
        }

        public void LoadMenu(TreeNodeCollection tnc, int ParentID)
        {
            int j = 0;
            if (channel != null)
            {
                while (j < channel.Rows.Count)
                {
                    DataRow dr = channel.Rows[j];
                    string name = dr["Name"].ToString();
                    string channelID = dr["ChannelID"].ToString();
                    string language = dr["Language"].ToString();
                    if (language == "0")
                        name = "VN | " + name;
                    else
                        name = "EN | " + name;
                    string link = "EditChannel.aspx?ChannelID=" + channelID;
                    string parentID = dr["ParentID"].ToString();
                    if (int.Parse(parentID) == ParentID)
                    {
                        channel.Rows.Remove(dr);
                        TreeNode tn = new TreeNode(name, channelID, null, link,"");
                        tn.SelectAction = TreeNodeSelectAction.Expand;
                        tnc.Add(tn);
                        this.LoadMenu(tn.ChildNodes, int.Parse(channelID));
                        continue;
                    }
                    j++;
                }
            }
        }

    }
}